package com.walkline.weather.dao;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Vector;

import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.walkline.util.Function;
import com.walkline.weather.WeatherException;
import com.walkline.weather.WeatherSDK;
import com.walkline.weather.inf.Place;

public class YahooPlaces extends YahooWeatherObject implements com.walkline.weather.inf.Places
{
	private int _start = 0;
	private int _count = 0;
	private int _total = 0;
	private Vector _places = new Vector();

	public YahooPlaces(WeatherSDK pWeather, StringBuffer pBuffer) throws WeatherException
	{
		super(pWeather, pBuffer);

		try {
			ByteArrayInputStream inputStream = new ByteArrayInputStream(pBuffer.toString().getBytes());
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder builder = factory.newDocumentBuilder();
	        //InputStream inputStream = getClass().getResourceAsStream("/xml/places_tianjin.xml");
	        Document document = builder.parse(inputStream);

	        NodeList rootNodeList = document.getElementsByTagName("places");
	        Node rootNode = rootNodeList.item(0);

	        if (rootNode.getNodeName().equalsIgnoreCase("places") && rootNode.hasAttributes())
	        {
	        	NamedNodeMap places = rootNode.getAttributes();
	        	_start = Integer.parseInt(places.getNamedItem("yahoo:start").getNodeValue());
	        	_count = Integer.parseInt(places.getNamedItem("yahoo:count").getNodeValue());
	        	_total = Integer.parseInt(places.getNamedItem("yahoo:total").getNodeValue());
	        }

	        NodeList nodeList = rootNode.getChildNodes();

	        for (int i=0; i<nodeList.getLength(); i++)
	        {
	        	Place place= new YahooPlace(nodeList.item(i));
	        	_places.addElement(place);
	        }
		} catch (Exception e) {Function.errorDialog(e.toString());}
	}

	public int getStart() {return _start;}

	public int getCount() {return _count;}

	public int getTotal() {return _total;}

	public Vector getPlaces() {return _places;}
}